package com.zjj.lbw.ai.old.interviiew;

import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 大都督周瑜（微信: dadudu6789）
 */
@Component
public class InterviewService {

    @Value("classpath:Java基础面试题.md")
    private Resource resource;

    @Autowired
    private VectorStore vectorStore;

    public List<Document> loadText() {

        // 读取文件内容
        TextReader textReader = new TextReader(resource);
        List<Document> documents = textReader.get();

        // 解析文件内容
        MarkdownSplitter textSplitter = new MarkdownSplitter();
        List<Document> list = textSplitter.apply(documents);

        // 将问题提取出来存入Metadata
        list.forEach(document -> {
            String title = document.getContent().split("==title==")[0];
            String replace = title.replace("##", "");
            document.getMetadata().put("question", replace.trim());
        });

        // 向量化以及向量存储
        vectorStore.add(list);

        return list;
    }


    public List<Document> search(String question){

        // 先查元数据
        SearchRequest metaSearchRequest = SearchRequest
                .query(question)
                .withTopK(3)
                .withSimilarityThreshold(0.9)
                .withFilterExpression(String.format("question in ['%s']", question));

        List<Document> metaDocuments = vectorStore.similaritySearch(metaSearchRequest);
        if (!CollectionUtils.isEmpty(metaDocuments)) {
            return metaDocuments;
        }

        // 元数据没查到在相似搜索
        SearchRequest searchRequest = SearchRequest
                .query(question)
                .withTopK(3)
                .withSimilarityThreshold(0.9);

        return vectorStore.similaritySearch(searchRequest);
    }
}
